/**
 * 
 */
package ca.lscs.web;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import ca.lscs.dal.DuplicateUsernameException;
import ca.lscs.dal.UserDao;
import ca.lscs.model.AppUser;
import ca.lscs.model.UserType;
import ca.lscs.web.utils.SessionUtils;

/**
 * @author Steve Pennington
 *
 */
@Controller
public class LoginController {
	
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.sendRedirect("/login");
		HttpSession session = request.getSession();
		SessionUtils.clearUserSession(session);
	}
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public ModelAndView handleLogin() throws DuplicateUsernameException {
		return new ModelAndView("login");
	}
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			String username = ServletRequestUtils.getRequiredStringParameter(request, "username");
			String password = ServletRequestUtils.getRequiredStringParameter(request, "password");
			try {
				password = AppUser.createPassword(password);
			} catch (NoSuchAlgorithmException e) {
				return new ModelAndView("login");
			}
			
			AppUser user = UserDao.getInstance().login(username, password);
			if(user == null) {
				return new ModelAndView("login"); 
			} else {
				HttpSession session = request.getSession(true);
				SessionUtils.putUserSession(session, user);
				if(user.getType() == UserType.ADMIN) {
					response.sendRedirect("/admin");
				} else {
					response.sendRedirect("/");
				}
				return null;
			}
			
		} catch(ServletRequestBindingException e) {
			return new ModelAndView("login");
		}
		
	}

}
